var express = require('express');
var router = express.Router();
var { userModel } = require('../database/models/userModel')
var bcrypt = require('bcryptjs');
var salt = bcrypt.genSaltSync(10); //盐值
var jwt = require('jsonwebtoken')
var secret = 'asdelfka;lsdkjf;alskjdfpla46464asdfasdf' //私钥

router.post('/', function(req, res, next) { //注册
  console.log(req.body);
  let {username,password} = req.body
  userModel.find({username}).then(results=>{
    if(results.length){ //账号被占用
      res.send({
        code:2,
        msg:'账号已被占用，请重试'
      })
      return
    }
    var hash = bcrypt.hashSync(password, salt); //密码加密
    new userModel({ //用户新增
      username,
      'password':hash
    }).save().then(results=>{
      res.send({
        code:1,
        msg:'注册成功'
      })
    })
  })
});


// 登录
router.get('/', function(req, res, next) {
  console.log(req.query);
  let {username,password} = req.query
  userModel.find({username}).then(results=>{
    if(!results.length){ //账号不存在
      res.send({
        code:2,
        msg:'账号不存在，请注册'
      })
      return
    }
    let hash = results[0].password //提取当前用户的加密密码
    let bool = bcrypt.compareSync(password,hash) //密码比对
    if(!bool){
      res.send({
        code:3,
        msg:'密码错误，请重试'
      })
      return
    }
    let data = results[0]
    data.password = ''
    //签发token
    let token = jwt.sign({
      time:Date.now(),  //记录签发时间
      // limit:7*24*60*60*1000
      limit:30*60*1000   //约定有效时长
    },secret)
    res.send({
      code:1,
      msg:'登录成功',
      data,
      token
    })
  })
});

router.put('/',(req,res)=>{ //更新用户信息
  console.log(req.query); //被更新的目标条件 { _id: '62a946ace6c328bcb547f8c3' }
  console.log(req.body); //新数据包  { avatar: '/uploads/tbh5temubzj1655366084299.png' }
  userModel.updateOne(req.query,req.body).then(results=>{
    res.send({
      code:1,
      msg:'用户信息更新成功'
    })
  })
})

module.exports = router;
